package com.ruoyi.web.controller.gcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.SjProcessConfig;
import com.ruoyi.gcgl.domain.SjProjectPeople;
import com.ruoyi.gcgl.domain.YyProject;
import com.ruoyi.gcgl.domain.YyProjectChange;
import com.ruoyi.gcgl.service.IGcCustomerService;
import com.ruoyi.gcgl.service.ISjProcessConfigService;
import com.ruoyi.gcgl.service.ISjProjectPeopleService;
import com.ruoyi.gcgl.service.IYyProjectChangeService;
import com.ruoyi.gcgl.service.IYyProjectService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;

/**
 * 项目施工变更单Controller
 * 
 * @author ruoyi
 * @date 2025-08-07
 */
@Controller
@RequestMapping("/yy/change")
public class YyProjectChangeController extends BaseController
{
    private String prefix = "yy/change";

    @Autowired
    private IYyProjectChangeService sjProjectChangeService;
    @Autowired
    private IYyProjectService gcProjectService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private IGcCustomerService gcCustomerService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Autowired
    private ISjProcessConfigService sjProcessConfigService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISjProjectPeopleService sjProjectPeopleService;
    
    final String processCode = "sjbiangengdan";

    @GetMapping()
    public String change()
    {
        return prefix + "/change";
    }

    /**
     * 查询项目施工变更单列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YyProjectChange sjProjectChange)
    {
        startPage();
        sjProjectChange.setDeleteFlag(1);
        
        //角色数据权限 ==根据用户定义的数据权限查看项目数据
        List<SysRole> roles = getSysUser().getRoles();
        List<Long> roleIds = new ArrayList<Long>();
        for(SysRole obj:roles){
        	roleIds.add(obj.getRoleId());
        }
        
        int count = roleService.selectCountRoleDeptByRoleId(roleIds);
        if(count != 0){
        	//看部门
        	sjProjectChange.setRoleIds(roleIds);
        }else{
        	//看个人
        	if(getSysUser().isShowRoleIds(roleIds)){
        		sjProjectChange.setOwnerId(getUserId());
            }
        }
        //----
        
        List<YyProjectChange> list = sjProjectChangeService.selectSjProjectChangeList(sjProjectChange);
        return getDataTable(list);
    }

    /**
     * 导出项目施工变更单列表
     */
    @Log(title = "项目施工变更单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YyProjectChange sjProjectChange)
    {
    	sjProjectChange.setDeleteFlag(1);
        List<YyProjectChange> list = sjProjectChangeService.selectSjProjectChangeList(sjProjectChange);
        ExcelUtil<YyProjectChange> util = new ExcelUtil<YyProjectChange>(YyProjectChange.class);
        return util.exportExcel(list, "项目施工变更单数据");
    }

    /**
     * 新增项目施工变更单
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") Long id, ModelMap mmap)
    {
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	mmap.put("owner", getLoginName());
    	mmap.put("ownerId", getUserId());
    	mmap.put("dept", getSysUser().getDept().getDeptName());
    	mmap.put("deptId", getSysUser().getDept().getDeptId());
    	
    	//下一级审核人
        List<SjProcessConfig> configlis = returnUser(getSysUser().getDept().getDeptId());
        mmap.put("approveid", configlis.get(0).getLevel1id());
        mmap.put("approvename", configlis.get(0).getLevel1name());
        return prefix + "/add";
    }

    /**
     * 新增保存项目施工变更单
     */
    @Log(title = "项目施工变更单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YyProjectChange sjProjectChange)
    {
    	sjProjectChange.setStatus(1);//状态1
    	sjProjectChange.setDeleteFlag(1);
    	sjProjectChange.setCreateUser(getLoginName());
    	sjProjectChange.setCreateAt(new Date());
    	sjProjectChange.setUpdateUser(getLoginName());
    	sjProjectChange.setUpdateAt(new Date());
        return toAjax(sjProjectChangeService.insertSjProjectChange(sjProjectChange));
    }

    /**
     * 修改项目施工变更单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        YyProjectChange sjProjectChange = sjProjectChangeService.selectSjProjectChangeById(id);
        
        if(sjProjectChange.getZlwj()!=null && !sjProjectChange.getZlwj().equals("")){
        	String[] zlis = sjProjectChange.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zlwjvo", file);
        }else{
        	mmap.put("zlwjvo", "");
        }
        
        mmap.put("sjProjectChange", sjProjectChange);
        
        //下一级审核人
        List<SjProcessConfig> configlis = returnUser(getSysUser().getDept().getDeptId());
        mmap.put("approveid", configlis.get(0).getLevel1id());
        mmap.put("approvename", configlis.get(0).getLevel1name());
        return prefix + "/edit";
    }

    /**
     * 修改保存项目施工变更单
     */
    @Log(title = "项目施工变更单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YyProjectChange sjProjectChange)
    {
    	sjProjectChange.setUpdateUser(getLoginName());
    	sjProjectChange.setUpdateAt(new Date());
        return toAjax(sjProjectChangeService.updateSjProjectChange(sjProjectChange));
    }

    /**
     * 删除项目施工变更单
     */
    @Log(title = "项目施工变更单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sjProjectChangeService.deleteSjProjectChangeByIds(ids));
    }
    
    @GetMapping("/p4change/{id}")
    public String p4change(ModelMap mmap,@PathVariable("id") Long id)
    {
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	//判断是成员，还是管理员
    	List<SysRole> roles = getSysUser().getRoles();
        List<Long> roleIds = new ArrayList<Long>();
        for(SysRole obj:roles){
        	roleIds.add(obj.getRoleId());
        }
        
    	//看个人
        int flag = 0;//成员
    	if(getSysUser().isShowRoleIds(roleIds)){
    		SjProjectPeople sjProjectPeople = new SjProjectPeople();
            sjProjectPeople.setDeleteFlag(1);
            sjProjectPeople.setGcProjectid(id);
            sjProjectPeople.setCode(getUserId().toString());
            List<SjProjectPeople> peoplelis = sjProjectPeopleService.selectSjProjectPeopleList(sjProjectPeople);
            if(peoplelis!=null && peoplelis.size()>0){
            	for(SjProjectPeople po1:peoplelis){
                	if(po1.getpId()==0l){
                		flag = 1;//领导
                		break;
                	}
                }
            }
        }else{
        	flag = 1;//领导
        }
        mmap.put("flag", flag);
        return "yy/project/projectDetailChange";
    }

    /**
     * 查询项目施工变更单列表
     */
    @PostMapping("/p4list")
    @ResponseBody
    public TableDataInfo p4list(YyProjectChange sjProjectChange)
    {
        sjProjectChange.setDeleteFlag(1);
        List<YyProjectChange> list = sjProjectChangeService.selectSjProjectChangeList(sjProjectChange);
        
        for(YyProjectChange ms:list){
        	YyProject po = gcProjectService.selectGcProjectById(ms.getGcProjectid());
        	ms.setProjectName(po.getName());
        }
        return getDataTable(list);
    }
    
    @GetMapping("/changePrint/{id}")
    public String changePrint(@PathVariable("id") Long id, ModelMap mmap){
    	YyProjectChange sjProjectChange = sjProjectChangeService.selectSjProjectChangeById(id);
        
        if(sjProjectChange.getZlwj()!=null && !sjProjectChange.getZlwj().equals("")){
        	String[] zlis = sjProjectChange.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zlwjvo", file);
        }else{
        	mmap.put("zlwjvo", "");
        }
        
        mmap.put("sjProjectChange", sjProjectChange);
        return prefix + "/changePrint";
    }
    
    //---------------------审批方法
    //申请人部门PID
    private List<SjProcessConfig> returnUser(Long deptId){
    	SysDept dept = deptService.selectDeptById(deptId);
    	SjProcessConfig sjProcessConfig = new SjProcessConfig();
        sjProcessConfig.setDeleteFlag(1);
        sjProcessConfig.setCode(processCode);
        sjProcessConfig.setDeptId(dept.getParentId());
        List<SjProcessConfig> configlis = sjProcessConfigService.selectSjProcessConfigList(sjProcessConfig);
		
        if(configlis==null || configlis.size()==0){
        	SjProcessConfig sjProcessConfig1 = new SjProcessConfig();
        	sjProcessConfig1.setDeleteFlag(1);
        	sjProcessConfig1.setCode("morenliucheng");
            List<SjProcessConfig> configlis1 = sjProcessConfigService.selectSjProcessConfigList(sjProcessConfig1);
            return configlis1;
        }
        return configlis;
    }
    
    /**
     * 修改保存项目立项
     */
    @Log(title = "项目变更", businessType = BusinessType.UPDATE)
    @PostMapping("/edit4check")
    @ResponseBody
    public AjaxResult edit4check(YyProjectChange sjProjectChange){
    	sjProjectChange.setUpdateUser(getLoginName());
    	sjProjectChange.setUpdateAt(new Date());
        return toAjax(sjProjectChangeService.updateSjProjectChange4check(sjProjectChange));
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level1")
    public String level1(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            mmap.put("approveid", obj.getZyfzrId());
            mmap.put("approvename", obj.getZyfzr());
        }
        
        return prefix + "/level1check";
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level2")
    public String level2(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            mmap.put("approveid", obj.getSprId());
            mmap.put("approvename", obj.getSpr());
        }
        
        return prefix + "/level2check";
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level3")
    public String level3(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            mmap.put("approveid", obj.getJdfzrId());
            mmap.put("approvename", obj.getJdfzr());
        }
        
        return prefix + "/level3check";
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level4")
    public String level4(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            mmap.put("approveid", obj.getXmfzrId());
            mmap.put("approvename", obj.getXmfzr());
        }
        
        return prefix + "/level4check";
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level5")
    public String level5(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            mmap.put("approveid", obj.getSdfzrId());
            mmap.put("approvename", obj.getSdfzr());
        }
        
        return prefix + "/level5check";
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level6")
    public String level6(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            List<SjProcessConfig> configlis = returnUser(Long.valueOf(obj.getDeptId().toString()));
            mmap.put("approveid", configlis.get(0).getLevel7id());
            mmap.put("approvename", configlis.get(0).getLevel7name());
        }
        
        return prefix + "/level6check";
    }
    

    /**
     * 修改单据
     * @param taskid
     * @param mmap
     * @return
     */
    @GetMapping("/modify")
    public String modify(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectChange obj = sjProjectChangeService.selectSjProjectChangeById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
            	String[] zlis = obj.getZlwj().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zlwjvo", file);
            }else{
            	mmap.put("zlwjvo", "");
            }
        	mmap.put("obj", obj);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
        }
        
        return prefix + "/modifycheck";
    }
    
    /**
     * 修改项目施工变更单
     */
    @GetMapping("/uploadChange/{id}")
    public String updateChange(@PathVariable("id") Long id, ModelMap mmap)
    {
        YyProjectChange sjProjectChange = sjProjectChangeService.selectSjProjectChangeById(id);
        
        if(sjProjectChange.getZlwj()!=null && !sjProjectChange.getZlwj().equals("")){
        	String[] zlis = sjProjectChange.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zlwjvo", file);
        }else{
        	mmap.put("zlwjvo", "");
        }
        
        mmap.put("sjProjectChange", sjProjectChange);
        
        return prefix + "/uploadChange";
    }
    
    /**
     * 修改保存项目施工变更单
     */
    @Log(title = "项目施工变更单", businessType = BusinessType.UPDATE)
    @PostMapping("/editChange")
    @ResponseBody
    public AjaxResult editChangeSave(YyProjectChange sjProjectChange)
    {
    	sjProjectChange.setStatus(8);
    	sjProjectChange.setUpdateUser(getLoginName());
    	sjProjectChange.setUpdateAt(new Date());
        return toAjax(sjProjectChangeService.updateSjProjectChange4check(sjProjectChange));
    }
}